﻿import requests
import execjs


def get_params(word):
    with open('有道翻译.js', 'r', encoding='utf-8') as f:
        result = execjs.compile(f.read()).call('fanyi', word)
    return result


def get_trans_api(word, params):
    url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    headers = {
        'Origin': 'https://fanyi.youdao.com',
        'Referer': 'https://fanyi.youdao.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36'
    }
    cookies = {
        """
        首页的Set-Cookie
        """
    }
    data = {
        "i": word,
        "from": "AUTO",
        "to": "AUTO",
        "smartresult": "dict",
        "client": "fanyideskweb",
        "salt": params['salt'],
        "sign": params['sign'],
        "lts": params['lts'],
        "bv": params['bv'],
        "doctype": "json",
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "action": "FY_BY_REALTlME",
    }
    res = requests.post(url, headers=headers, data=data, cookies=cookies)
    print("原文===>", res.json()['translateResult'][0][0]['src'])
    print("翻译结果===>", res.json()['translateResult'][0][0]['tgt'])


word = 'what`s your name'
params = get_params(word)
result = get_trans_api(word, params)
